package com.sum.tea.xinlian.utils

import com.sum.tea.contants.AppConfig
import com.sum.tea.xinlian.bean.TagInfo
import com.uhf.api.cls.Reader

object TagUtils {
    fun processTagInfo(
        EPC: String,
        tfs: Reader.TAGINFO,
        keyu8: Int,
        myapp: AppConfig
    ): TagInfo {
        var key = EPC
        var epcstr = EPC
        var tid = ""
        var bid = ""

        // 根据keyu8处理EPC
        when (keyu8) {
            1 -> {
                key = key.substring(0, key.length - 4)
                bid = epcstr.substring(epcstr.length - 4)
                epcstr = epcstr.substring(0, epcstr.length - 4)
            }
            2 -> {
                key = key.substring(0, key.length - 24)
                tid = epcstr.substring(epcstr.length - 24)
                epcstr = epcstr.substring(0, epcstr.length - 24)
            }
            3 -> {
                key = key.substring(0, key.length - 4)
                bid = epcstr.substring(epcstr.length - 4)
                epcstr = epcstr.substring(0, epcstr.length - 4)
            }
        }

        if(epcstr.length < 24) {
            epcstr = String.format("%-24s", epcstr)
        }

        // 处理附加数据
        var emdstr = ""
        var rfu = ""

        if(tfs.EmbededDatalen > 0) {
            val out = CharArray(tfs.EmbededDatalen * 2)
            myapp.Mreader.Hex2Str(tfs.EmbededData, tfs.EmbededDatalen.toInt(), out)
            emdstr = String(out)
            if(keyu8 == 1) tid = emdstr
        }

        if(keyu8 != 0) {
            val out2 = CharArray(4)
            myapp.Mreader.Hex2Str(tfs.Res, 2, out2)
            rfu = String(out2)
        } else {
            rfu = (tfs.Res[1].toInt() and 0x3f).toString()
        }

        // 处理唯一标识
        if(myapp.isUniByEmd) {
            when {
                keyu8 == 2 -> key += tid
                emdstr.isNotEmpty() -> key += emdstr
            }
        }

        if(myapp.isUniByAnt) {
            key += tfs.AntennaID.toString()
        }

        return TagInfo(
            key = key,
            epcstr = epcstr,
            tid = tid,
            bid = bid,
            emdstr = emdstr,
            rfu = rfu,
            tagInfo = tfs
        )
    }
}